<?php

namespace App\Repository\Admin;

use App\Models\Admin\AdminUsers as model;
use App\Repository\BaseRepository;
use App\Repository\Commit\RoleRepository;


class AdminUsersRepository extends BaseRepository
{
    private $model;
    private $role;

    public function __construct()
    {
        $this->model = new model;
        $this->role = new RoleRepository();
        parent::__construct();
    }

    public function index($request)
    {
        $where['like'] = ['name', 'phone', 'company_name'];
        $cron['like'] = $this->getWhere($where['like'], $request);
        $cron['where']['admin_users.del_flag'] = 0;
        if (!empty($request->user->company_master_id)) {
            $cron['where'] = $this->getWhere(['company_master_id'], $request);
        }
        if (!empty($request['params']['beginTime']) && !empty($request['params']['endTime'])) {
            $cron['between']['admin_users.create_time'][] = $request['beginTime'];
            $cron['between']['admin_users.create_time'][] = $request['endTime'];
        }
        if ((empty($request->get('roleId')) || $request->get('roleId') != 1) && $request->user->role_id != 1) {
            $cron['where']['admin_users.shop_id'] = $request['user']['shop_id'];
        }
        if (!empty($request->get('roleId'))) {
            $cron['where']['admin_users.role_id'] = $request->get('roleId');
        }
        if (isset($request['status'])) {
            $cron['where']['admin_users.status'] = $request->get('status');
        }
        if (!empty($request->get('phonenumber'))) {
            $cron['like']['admin_users.phonenumber'] = $request->get('phonenumber');
        }
        if (!empty($request->get('userName'))) {
            $cron['like']['admin_users.user_name'] = $request->get('userName');
        }
        if (!empty($request->get('deptId'))) {
            $cron['where']['admin_users.dept_id'] = $request->get('deptId');
        }
        $cron['order']['orderby'] = isset($request['orderby']) ? $request['orderby'] : 'admin_users.id';
        $cron['order']['orderdir'] = isset($request['orderdir']) ? $request['orderdir'] : 'desc';
        $pageNums = 0;
        $cron['limit']['number'] = isset($request['pageSize']) ? ($request['pageSize']) : 10;
        if (isset($request['pageNum']) && !empty(($request['pageNum']))) {
            $pageNums = ($request['pageNum'] - 1) * $cron['limit']['number'];
        }
        $cron['limit']['start'] = $pageNums;
        $cron['join'][] = ['table' => 'dept', 'left' => 'dept_id', 'right' => ('admin_users.dept_id')];
        $cron['select'] = [('admin_users.*'), 'dept.dept_name as dept_name'];
        if ($request->user->role_id != 1) {
            $cron['where']['admin_users.shop_id'] = $request->user->shop_id;
        }
        $data = $this->search($this->model, $cron, 1, 10);
        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => $v) {
                $data['data'][$key] = usfirstArr($v);
            }
        }
        return $data;
    }

//手动更新自己的在线状态
    public function updateOnline($params)
    {
        $userId = intval($params['user']['id']);
        $online = $this->model->where('id', $userId)->value('online');
        if (isset($params['loadData']) && $params['loadData'] == 1) {
            return $this->returnMsg(200, '查询完成', ['online' => $online]);
        }
        $online = abs($online - 1);
        $this->model->where('id', $userId)->update(['online' => $online]);
        return $this->returnMsg(200, '执行完成', ['online' => $online]);
    }

    public function noInList($request)
    {
        $params = $request->all();
        if (!empty($request->get('roleId'))) {
            $cron['where'][] = ['role_id', '!=', $params['roleId']];
        }
        if (!empty($params['userName'])) {
            $cron['like'][] = ['username' => $params['userName']];
        }
        if (!empty($params['phonenumber'])) {
            $cron['where'][] = ['telphone', '=', $params['phonenumber']];
        }

        $cron['order']['orderby'] = isset($request['orderby']) ? $request['orderby'] : 'id';
        $cron['order']['orderdir'] = isset($request['orderdir']) ? $request['orderdir'] : 'desc';
        $pageNums = 0;
        $cron['limit']['number'] = isset($request['pagenums']) ? ($request['page_size']) : 10;
        if (isset($request['page']) && !empty(($request['page']))) {
            $pageNums = ($request['page'] - 1) * $cron['limit']['number'];
        }
        $cron['limit']['start'] = $pageNums;
        return $this->search($this->model, $cron, 1, 10);
    }

    //添加
    public function store($data)
    {
        //必填 字段
        $mustField = [
            'user_name',
            'password'
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'user_name' => '账号不能为空',
            'password' => '密码不能为空'
        ];

        if (!empty($data['post_ids'])) {
            $data['position_id'] = implode('.', $data['post_ids']);
            // unset($insertData['post_ids']);
        }
        if (empty($data['dept_id'])) {
            return $this->returnMsg(110, '请选者部门');
        }
        //        这个值也不是传过来了，根据dept_id查他的角色吧
//        if (!empty($data['role_ids'])) {
//            $data['role_id'] = implode('.', $data['role_ids']);
//            // unset($insertData['role_ids']);
//        }
        $ModelDept = new \App\Models\Dept();
        $deptData = $ModelDept->where(['dept_id' => $data['dept_id']])->select(['role_id'])->first();
        $data['role_id'] = str_replace(',', '.', $deptData['role_id']);
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        $insertData['user_name'] = trim($insertData['user_name']);
        //判断用户是否存在
        $isTrue = $this->model->where(['user_name' => $insertData['user_name']])->first();
        if ($isTrue) {
            return $this->returnMsg(3, '该用户已存在');
        }
        //密码加密
        if (!empty($insertData['password'])) {
            $passwd = $this->model->passwd($insertData['password']);
            $insertData['password'] = $passwd['passwd'];
            $insertData['passsalt'] = $passwd['salt'];
        }
        $insertData['shop_id'] = !empty($data['user']['shop_id']) ? $data['user']['shop_id'] : (!empty($data['user']['id']) ? $data['user']['id'] : 0);
        $insertData['supplier'] = $data['user']['supplier'] ?? '';
        $insertData['create_time'] = date('Y-m-d H:i:s');
        $res = $this->model->insert($insertData);
        if ($res) {
            return $this->returnMsg(200, '添加成功');
        }
        return $this->returnMsg(1, '添加失败');
    }

    //用户注册
    public function register($data)
    {
        //必填 字段
        $mustField = [
            'user_name',
            'password',
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'username' => '账号不能为空',
            'password' => '密码不能为空'
        ];
        // if (!empty($data['role_ids'])) {
        //   $data['role_id'] = implode('.', $data['role_ids']);
        //   // unset($insertData['role_ids']);
        // }
        // if (!empty($data['post_ids'])) {
        //   $data['position_id'] = implode('.', $data['post_ids']);
        //   // unset($insertData['post_ids']);
        // }
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        if ($data['confirm_password'] != $insertData['password']) {
            return $this->returnMsg(3, '两次密码不一致');
        }
        // 密码验证
        if ($data['confirm_password'] == '123456') {
            return $this->returnMsg(4, '密码太简单,请重新设置密码');
        }
        //判断用户是否存在
        $isTrue = $this->model->where(['user_name' => $insertData['user_name']])->first();
        if ($isTrue) {
            return $this->returnMsg(3, '该用户已存在');
        }
        //密码加密
        if (!empty($insertData['password'])) {
            $passwd = $this->model->passwd($insertData['password']);
            $insertData['password'] = $passwd['passwd'];
            $insertData['passsalt'] = $passwd['salt'];
        }
        // $insertData['shop_id'] = !empty($data->user->shop_id) ? $data->user->shop_id : (!empty($data->user->id) ? $data->user->id : 0);
        $insertData['create_time'] = date('Y-m-d H:i:s');
        $insertData['update_time'] = date('Y-m-d H:i:s');
        $insertData['role_id'] = 2;
        $insertData['nick_name'] = $insertData['user_name'];
        $insertData['supplier'] = productSuppiler(12); // 默认分销商
        $insertData['status'] = 1;
        $res = $this->model->insertGetId($insertData);
        if ($res) {
            $this->model->where('id', $res)->update(['shop_id' => $res]);
            return $this->returnMsg(200, '添加成功');
        }
        return $this->returnMsg(1, '添加失败');
    }

    //删除
    public function del($where)
    {
        if (empty($where)) {
            return $this->returnMsg(404, '未查询到该数据');
        }
        $this->model->where($where)->update(['del_flag' => 2]);
        return $this->returnMsg(200, '删除成功');
    }

    public function supervisorOptionsList($params)
    {
        $where = [];
        $where['eq']['status'] = 0;
        $where['eq']['shop_id'] = $params['user']['id'];
//        print_r($params);
        $rows = $this->model->searchWhere($where)->select(['id', 'nick_name'])->get()->toArray();
        return $this->returnMsg(200, '查询成功', $rows);
    }

//快速修改状态
    public function changeStatus($userId, $status)
    {
        $where = [
            'id' => $userId
        ];
        $update = [
            'status' => $status
        ];
        $this->model->where($where)->update($update);
        return $this->returnMsg(200, '操作成功');
    }

//    修改头像
    public function avatar($where, $avatar)
    {
        if (empty($avatar)) {
            return $this->returnMsg(100, '内容为空');
        }
        $res = $this->model->where($where)->update(['avatar' => $avatar]);
        if (false !== $res) {
            return $this->returnMsg(200, '修改成功', ['imgUrl' => $avatar]);
        }
        return $this->returnMsg(100, '操作失败');
    }

    public function resetUser($params)
    {
        if (empty($params['id'])) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($params['user_name'])) {
            return $this->returnMsg(1, '账号为空');
        }
        if (empty($params['nick_name'])) {
            return $this->returnMsg(1, '昵称为空');
        }
        if (empty($params['password'])) {
            return $this->returnMsg(1, '密码为空');
        }
        $where = ['id' => $params['id']];
        $isTrue = $this->model->where($where)->first();
        if (!$isTrue) {
            return $this->returnMsg(10, '未查询到用户信息');
        }
        $optionalFields = $this->model->getTableField();
        $params = $this->getRealData($params, [], $optionalFields, []);

        $passwd = $this->model->passwd($params['password']);
        $params['password'] = $passwd['passwd'];
        $params['passsalt'] = $passwd['salt'];
        $res = $this->model->where($where)->update($params);
        if ($res) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(2, '修改异常');
    }

    //修改
    public function edit($where, $data, $isMust = false)
    {
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        $isTrue = $this->model->where($where)->first();
        if (!$isTrue) {
            return $this->returnMsg(10, '未查询到用户信息');
        }
        // 验证密码
        if (!empty($data['oldPassword'])) {
            $old = $this->model->verifyPasswd($data['oldPassword'], $isTrue->passsalt);
            if ($old != $isTrue->password) {
                return $this->returnMsg(11, '密码不正确');
            }
        }
        if (!empty($data['oldExpPassword']) && !empty($isTrue->exp_password)) {
            $old = $this->model->verifyPasswd($data['oldExpPassword'], $isTrue->exp_passsalt);
            if ($old != $isTrue->exp_password) {
                return $this->returnMsg(11, '导出密码不正确');
            }
        }
//      是修改内容,不是修改密码
        if (empty($data['password']) && empty($data['exp_password'])) {
//        这个值也不是传过来了，根据dept_id查他的角色吧,自己修改自己资料的时候没有这个参数
            if (!empty($data['dept_id'])) {
                $ModelDept = new \App\Models\Dept();
                $deptData = $ModelDept->where(['dept_id' => $data['dept_id']])->select(['role_id'])->first();
                $data['role_id'] = str_replace(',', '.', $deptData['role_id']);
            }
//        if (!empty($data['role_ids'])) {
//            $data['role_id'] = implode('.', $data['role_ids']);
//            // unset($insertData['role_ids']);
//        }
//    这个旧的部门id好像已经弃用了，用了dept_id
            if (!empty($data['post_ids'])) {
                $data['position_id'] = implode('.', $data['post_ids']);
                // unset($insertData['post_ids']);
            }
        }
        // var_dump($data);
        //过滤字段
        $optionalFields = $this->model->getTableField();
        $field = $this->getRealData($data, [], $optionalFields, []);
        //用户姓名不能修改
        if (isset($field['username'])) {
            unset($field['username']);
        }
        //密码加密
        if (!empty($field['password'])) {
            $passwd = $this->model->passwd($field['password']);
            $field['password'] = $passwd['passwd'];
            $field['passsalt'] = $passwd['salt'];
        }
        // 导出
        if (!empty($field['exp_password'])) {
            $passwd = $this->model->expPasswd($field['exp_password'], '');
            $field['exp_password'] = $passwd['passwd'];
            $field['exp_passsalt'] = $passwd['salt'];
        }
        // if (empty($field['password']) && !empty($field['passsalt'])) {
        //   unset($field['passsalt']);
        // }
        if (empty($field['password'])) {
            unset($field['passsalt']);
            unset($field['password']);
        }

        //先查询是否存在
        $field['update_time'] = date('Y-m-d H:i:s');
        if (empty($field['login_date'])) {
            $field['login_date'] = date('Y-m-d H:i:s');
        }
        if (empty($field['create_time'])) {
            $field['create_time'] = date('Y-m-d H:i:s');
        }
        // var_dump($field, 1111111);
        $res = $this->model->where($where)->update($field);
        if ($isMust && $res) {
            return $this->returnMsg(200, '修改成功');
        }
        if (!$isMust) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(3, '请重新修改');
    }

    //查看  存入缓存
    public function sel($where = [], $page = 1, $limit = 10, $user = array())
    {
        //过滤查询条件
        //权限限制
        if ($user) {
            $where['liker'] = [
                'dept_str' => $user['dept_str'] . '%'
            ];
        }
        $where['select'] = ['user.*', 'role.name as roel_name'];
        $where['join'] = [
            [
                'join' => 'leftJoin',
                'table' => 'role',
                'left' => 'id',
                'right' => 'user.role_id',
            ]
        ];
        $res = $this->search($this->model, $where, $page, $limit);
        return $res;
    }

    //查询 单条数据
    public function oneSel($where, $isUp = true, $field = ['*'])
    {
        $data = $this->model->where($where)->select($field)->first();
        if (!empty($data) && $isUp) {
            $data = usfirstArr($data);
        }
        return $data;
    }

    public function getOne($where, $field = ['*'])
    {
        return $this->model->where($where)->select($field)->first();
    }

    public function oneSelRole($where)
    {
        $data = $this->model->where($where)->first();
        if (!empty($data)) {
            $data = usfirstArr($data);
            $data['roles'] = [];
            if (!empty($data['roleId'])) {
                $roleId = explode('.', $data['roleId']);
                $whereRole = $roleId;
                // var_dump($whereRole);
                $data['roles'] = $this->role->getAllDataUser([], $whereRole);
            }
        }
        return $data;
    }

    //验证码验证
    public function verifyPasswd($passwd, $numd)
    {
        return $this->model->verifyPasswd($passwd, $numd);
    }

    public function ThisModel()
    {
        return $this->model;
    }

    // 获取用户的
    public function getUserOper($where)
    {
    }

    // 扣除用户的资金
    public function deductMoney($id, $money)
    {
        if (empty($money)) {
            return '资金金额不能为空';
        }
        $rs = $this->model->where(['id' => $id])->first();
        if (empty($rs)) {
            return '未查询到用户信息';
        }
        // $update = false;
        // if ($money < 0 && $rs->money > abs($money)) {
        //   $update = $this->model->where(['id' => $rs])->decrement('money', $money);
        // }
        // if ($money > 0) {
        //   // var_dump($money, 4444444);

        // }
        if ($money < 0 && ($rs->money + $money) < 0) {
            // return '资金不足';
        }
        $update = $this->model->where(['id' => $id])->update(['money' => ($rs->money + $money)]);
        // $log = DB::getQueryLog();
        if ($update) {
            return [
                'after_money' => $rs->money + $money,
                'befor_money' => $rs->money,
            ];
        }

        return $update;
    }
}
